package org.swust.sysmonitorapp.service.handler;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.swust.sysmonitorapp.service.IDeviceStatusService;

@Slf4j
public class DeviceStatusHandler implements MessageHandler {

    private final IDeviceStatusService deviceStatusService;

    public DeviceStatusHandler(IDeviceStatusService deviceStatusService) {
        this.deviceStatusService = deviceStatusService;
    }

    @Override
    public void handle(JsonNode root) {
        JsonNode header = root.path("notify_data").path("header");
        JsonNode body = root.path("notify_data").path("body");

        String deviceId = header.path("device_id").asText();
        String status = body.path("status").asText();
        String lastOnlineTime = body.path("last_online_time").asText();

        log.info("设备状态更新: deviceId={}, status={}, lastOnlineTime={}", deviceId, status, lastOnlineTime);

        // 调用已有的服务更新设备状态
        boolean success = deviceStatusService.updateDeviceStatus(deviceId, status);
        if (success) {
            log.info("设备状态更新成功: deviceId={}", deviceId);
        } else {
            log.warn("设备状态更新失败: deviceId={}", deviceId);
        }
    }
}

